package com.jlastu.znb.view;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.security.identity.PersonalizationData;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import com.jlastu.znb.R;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class PersonalActivity extends AppCompatActivity {
    private static final int SELECT_PICTURE = 2;
    private ImageView mBack;
    private ImageView mUserPicture;
    private LinearLayout mPicture;
    private LinearLayout mName;
    private LinearLayout mAge;
    private LinearLayout mAddress;
    private TextView mOutputName;
    private TextView mAddressTextView;
    private TextView mOutputAge;

    private Bitmap loadAvatarFromInternalStorage() {
        SharedPreferences sharedPreferences = getSharedPreferences("UserInfo", MODE_PRIVATE);
        String photoPath = sharedPreferences.getString("PHOTO_PATH_KEY", null); // 如果没有找到则返回null
        if (photoPath != null && new File(photoPath).exists()) {
            try {
                return BitmapFactory.decodeFile(photoPath);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null; // 如果没有找到图片或加载失败，返回null
    }
    @SuppressLint("WrongViewCast")
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_personal);
        mBack = findViewById(R.id.back);
        mBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        mPicture = findViewById(R.id.picture);
        mPicture.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                openImageChooser();
            }
        });
        mUserPicture = findViewById(R.id.user_avatar);
        mUserPicture.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                openImageChooser();
            }
        });
        mName = findViewById(R.id.name);
        mName.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(PersonalActivity.this, ModifyingInformationActivity.class);
                startActivityForResult(intent, 1);
            }
        });
        mOutputName = findViewById(R.id.output_name);
        SharedPreferences sharedPreferences = getSharedPreferences("UserInfo", MODE_PRIVATE);
        String savedName = sharedPreferences.getString("NAME_KEY", "");
        mOutputName.setText(savedName);
        // 加载并显示头像
        Bitmap avatarBitmap = loadAvatarFromInternalStorage();
        if (avatarBitmap != null) {
            mUserPicture.setImageBitmap(avatarBitmap);
        }
        mAge = findViewById(R.id.age);
        mAge.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showAgePicker();
            }
        });
        //收购地址选择点击事件
        mAddress = findViewById(R.id.address);
        mAddress.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showAddressPicker();
            }
        });
        mAddressTextView = findViewById(R.id.output_address);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case 1: // 姓名修改的请求码
                if (resultCode == RESULT_OK && data != null) {
                    String receivedText = data.getStringExtra("NAME_KEY");
                    updateNameInSharedPreferences(receivedText);
                    updateNameOnUI(receivedText);
                }
                break;
            case SELECT_PICTURE: // 头像选择的请求码
                if (resultCode == RESULT_OK && data != null) {
                    Uri selectedImageUri = data.getData();
                    if (selectedImageUri != null) {
                        try {
                            InputStream imageStream = getContentResolver().openInputStream(selectedImageUri);
                            Bitmap bitmap = BitmapFactory.decodeStream(imageStream);
                            updateAvatarOnUI(bitmap);
                            saveImageToInternalStorage(selectedImageUri, "user_avatar.jpg"); // 保存头像并更新SharedPreferences
                        } catch (FileNotFoundException e) {
                            e.printStackTrace();
                            // 可以在这里给用户一个错误提示
                        }
                    }
                }
                break;
        }
    }

    private void openImageChooser() {
        Intent intent = new Intent();
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(Intent.createChooser(intent, "选择图片"), SELECT_PICTURE);
    }

    private void saveImageToInternalStorage(Uri imageUri, String fileName) {
        try {
            InputStream imageStream = getContentResolver().openInputStream(imageUri);
            // 使用文件输出流将图片保存到内部存储
            File storageDir = getExternalFilesDir(null);
            if (storageDir != null) {
                File imageFile = new File(storageDir, fileName);
                FileOutputStream out = new FileOutputStream(imageFile);
                byte[] buffer = new byte[1024];
                int length;
                while ((length = imageStream.read(buffer)) > 0) {
                    out.write(buffer, 0, length);
                }
                out.close();
                imageStream.close();

                // 更新SharedPreferences，保存图片路径
                SharedPreferences sharedPreferences = getSharedPreferences("UserInfo", MODE_PRIVATE);
                SharedPreferences.Editor editor = sharedPreferences.edit();
                editor.putString("PHOTO_PATH_KEY", imageFile.getAbsolutePath());
                editor.apply();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void updateNameInSharedPreferences(String name) {
        SharedPreferences sharedPreferences = getSharedPreferences("UserInfo", MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString("NAME_KEY", name);
        editor.apply();
    }

    // 更新UI上的姓名显示
    private void updateNameOnUI(String name) {
        mOutputName.setText(name);
    }

    // 更新UI上的头像显示
    private void updateAvatarOnUI(Bitmap bitmap) {
        runOnUiThread(() -> mUserPicture.setImageBitmap(bitmap));
    }

    private void showAgePicker() {
        // 创建 AlertDialog
        final AlertDialog.Builder builder = new AlertDialog.Builder(PersonalActivity.this);
        LayoutInflater inflater = getLayoutInflater();
        View dialogView = inflater.inflate(R.layout.age_select, null); // 使用您的价格选择布局
        builder.setView(dialogView);
        final AlertDialog dialog = builder.create();

        // 获取 RadioGroup 和其他控件
        final RadioGroup radioGroup = dialogView.findViewById(R.id.radio_group);
        final TextView determineButton = dialogView.findViewById(R.id.determine);
        ImageView closeButton = dialogView.findViewById(R.id.close_button);
        final TextView ageTextView = findViewById(R.id.output_age); // 确保这个ID与您的布局文件中定义的相符

        // 为 RadioGroup 设置监听器，以便在选项变化时更新界面
        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                // 当选择变化时，获取选中的RadioButton的文本，并更新priceTextView
                RadioButton selectedRadioButton = radioGroup.findViewById(checkedId);
                ageTextView.setText(selectedRadioButton.getText());
            }
        });

        // 为关闭按钮设置点击事件
        closeButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });

        // 为确定按钮设置点击事件
        determineButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 获取选中的年龄
                String selectedAge = ageTextView.getText().toString();

                // 更新SharedPreferences，保存年龄
                SharedPreferences sharedPreferences = getSharedPreferences("UserInfo", MODE_PRIVATE);
                SharedPreferences.Editor editor = sharedPreferences.edit();
                editor.putString("AGE_KEY", selectedAge);
                editor.apply();

                dialog.dismiss();
            }
        });

        // 显示对话框
        dialog.show();
    }

    private void showAddressPicker() {
        // 假设这是从数据库或其他数据源获取的省市区数据
        Map<String, List<String>> provinceCityMap = new HashMap<>();
        Map<String, List<String>> cityDistrictMap = new HashMap<>();

        // 示例数据填充
        provinceCityMap.put("吉林省", Arrays.asList("长春市", "吉林市", "四平市"));
        provinceCityMap.put("云南省", Arrays.asList("昆明市", "曲靖市", "玉溪市"));

        // 假设每个城市下都有一些区域
        cityDistrictMap.put("长春市", Arrays.asList("南关区", "宽城区", "朝阳区"));
        cityDistrictMap.put("吉林市", Arrays.asList("昌邑区", "龙潭区", "船营区"));
        cityDistrictMap.put("昆明市", Arrays.asList("五华区", "盘龙区", "西山区"));
        cityDistrictMap.put("曲靖市", Arrays.asList("麒麟区", "沾益区", "马龙区"));

        final AlertDialog.Builder builder = new AlertDialog.Builder(PersonalActivity.this);
        LayoutInflater inflater = getLayoutInflater();
        View dialogView = inflater.inflate(R.layout.address_select, null);
        builder.setView(dialogView);
        final AlertDialog dialog = builder.create();

        // 初始化 Spinner
        final Spinner spinnerProvince = dialogView.findViewById(R.id.spinner_province);
        final Spinner spinnerCity = dialogView.findViewById(R.id.spinner_city);
        final Spinner spinnerDistrict = dialogView.findViewById(R.id.spinner_district);

        // 填充省份 Spinner
        ArrayAdapter<String> provincesAdapter = new ArrayAdapter<>(this,
                android.R.layout.simple_spinner_item, new ArrayList<>(provinceCityMap.keySet()));
        provincesAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinnerProvince.setAdapter(provincesAdapter);

        // 省份 Spinner 监听器
        spinnerProvince.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                String selectedProvince = parent.getItemAtPosition(position).toString();
                List<String> cities = provinceCityMap.get(selectedProvince);
                // 更新城市 Spinner
                ArrayAdapter<String> citiesAdapter = new ArrayAdapter<>(
                        PersonalActivity.this,
                        android.R.layout.simple_spinner_item, cities);
                citiesAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                spinnerCity.setAdapter(citiesAdapter);
                // 重置区域 Spinner
                spinnerDistrict.setAdapter(new ArrayAdapter<>(
                        PersonalActivity.this,
                        android.R.layout.simple_spinner_item, new ArrayList<>()));
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                // Do nothing
            }
        });

        // 填充城市 Spinner
        ArrayAdapter<String> citiesAdapter = new ArrayAdapter<>(this,
                android.R.layout.simple_spinner_item, new ArrayList<>(provinceCityMap.values().iterator().next()));
        citiesAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinnerCity.setAdapter(citiesAdapter);

        // 城市 Spinner 监听器
        spinnerCity.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                String selectedCity = parent.getItemAtPosition(position).toString();
                List<String> districts = cityDistrictMap.get(selectedCity);
                // 更新区域 Spinner
                ArrayAdapter<String> districtsAdapter = new ArrayAdapter<>(
                        PersonalActivity.this,
                        android.R.layout.simple_spinner_item, districts);
                districtsAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                spinnerDistrict.setAdapter(districtsAdapter);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                // Do nothing
            }
        });

        // 设置对话框按钮
        TextView determineButton = dialogView.findViewById(R.id.determine);
        determineButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 获取选中的省市区
                String selectedProvince = spinnerProvince.getSelectedItem().toString();
                String selectedCity = spinnerCity.getSelectedItem().toString();
                String selectedDistrict = spinnerDistrict.getSelectedItem().toString();

                // 构建完整的地址字符串
                String fullAddress = selectedProvince + " " + selectedCity + " " + selectedDistrict;

                // 更新SharedPreferences，保存地址
                SharedPreferences sharedPreferences = getSharedPreferences("UserInfo", MODE_PRIVATE);
                SharedPreferences.Editor editor = sharedPreferences.edit();
                editor.putString("ADDRESS_KEY", fullAddress);
                editor.apply();

                // 更新UI上的地址显示
                mAddressTextView.setText(fullAddress);

                dialog.dismiss();
            }
        });
        ImageView closeButton = dialogView.findViewById(R.id.close_button);
        closeButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss(); // 关闭对话框
            }
        });

        // 显示对话框
        dialog.show();

    }
}
